//
//  JKHorizonView.m
//  JackToolsBox
//
//  Created by Jack Xue on 2019/12/24.
//  Copyright © 2019 Jack Xue. All rights reserved.
//

#import "JKHorizonView.h"

@interface JKHorizonView()<UIScrollViewDelegate>{
    UIScrollView *_baseScrollView;
    NSMutableDictionary *_subviewManager;
    NSMutableSet *_reusePool;            //重用池
}
@end

@implementation JKHorizonView
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        _subviewManager = [NSMutableDictionary dictionary];
        _reusePool = [[NSMutableSet alloc]init];
        
        _baseScrollView = [[UIScrollView alloc]initWithFrame:CGRectZero];
        _baseScrollView.clipsToBounds = NO; //调试用
        if (@available(iOS 11.0, *)) {
            _baseScrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        } else {
            //找到controller然后
        }
        _baseScrollView.delegate = self;
        _baseScrollView.pagingEnabled = YES;
        [self addSubview:_baseScrollView];
    }
    return self;
}

-(void)layoutSubviews{
    [super layoutSubviews];
    NSLog(@"layoutSubviews");
    _baseScrollView.frame = self.bounds;
    if ([self.dataSource respondsToSelector:@selector(numberOfItemsInHorizonView:)] && [self.dataSource respondsToSelector:@selector(horizonView:itemAtIndex:)]) {
        //默认获取itemSize，默认与_baseScrollView一样
        if (CGSizeEqualToSize(_itemSize, CGSizeZero)) {
            _itemSize = _baseScrollView.frame.size;
        }

        NSInteger count = [self.dataSource numberOfItemsInHorizonView:self];
        if (count <= 0) {
            return;
        }
        [_baseScrollView setContentSize:CGSizeMake(_baseScrollView.frame.size.width * count, 0)];
        for (NSInteger i = 0; i < (count > 3 ? 3 : count); i++) {
            //最多添加3个
            JkHorizonItem *newItem = [self.dataSource horizonView:self itemAtIndex:i];
            newItem.frame = CGRectMake(i * _baseScrollView.bounds.size.width, 0, _baseScrollView.bounds.size.width, _itemSize.height);
            [_baseScrollView addSubview:newItem];
            
            [_subviewManager setValue:newItem forKey:[NSString stringWithFormat:@"%ld",i]];
        }
    }
}

#pragma mark - UIScrollViewDelegate
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    NSLog(@"+++%f",scrollView.contentOffset.x);

}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    //在此处计算需要显示的item(-1...1)+index
    NSInteger index = scrollView.contentOffset.x / self.bounds.size.width;
    if (index > 0 && index < [self.dataSource numberOfItemsInHorizonView:self] - 1) {
        //当前需要显示的范围showRange
        NSRange showRange = NSMakeRange(-1 + index, 3);
        
        //添加需要显示的item，并将离开屏幕的item放入重用池
        for (NSInteger i = showRange.location; i <= showRange.location + showRange.length; i++) {
            //_subManger 管理当前正在显示的items
            JkHorizonItem *item = [_subviewManager valueForKey:[NSString stringWithFormat:@"%ld",(long)i]];
            if (!item) {
                //需要显示该item但是还没有创建这个item
                item = [self.dataSource horizonView:self itemAtIndex:i];    //如果return为nil怎么办
                [_subviewManager setValue:item forKey:[NSString stringWithFormat:@"%ld",(long)i]];
                item.frame = CGRectMake(i * self.bounds.size.width, 0, self.bounds.size.width, self.bounds.size.height);
                [_baseScrollView addSubview:item];
            }
            
            //将不用的cell放到重用池中
            NSArray *subCells = [_subviewManager allKeys];
            for (NSString *string in subCells) {
                if (!NSLocationInRange([string integerValue], showRange)) {
                    //可以放进重用池的cell
                    JkHorizonItem *removeItem = [_subviewManager valueForKey:string];
                    [removeItem removeFromSuperview];
                    [_reusePool addObject:removeItem];
                    [_subviewManager removeObjectForKey:string];
                }
            }//@end - 重用池循环
        }
    }//@end - 判断index合理范围
    
}

-(void)reloadData{
    
}

-(JkHorizonItem*)dequeueReusableItem{
    JkHorizonItem *reuseItem = nil;
    reuseItem = [_reusePool anyObject];
    if (reuseItem) {
        [_reusePool removeObject:reuseItem];
        return reuseItem;
    }else{
        return nil;
    }
}



@end
